Reverse Level Order Traversal (easy)

Problem Statement #

Given a binary tree, populate an array to represent its level-by-level traversal in reverse order, i.e., the lowest level comes first. You should populate the values of all nodes in each level from left to right in separate sub-arrays.

Example 1:

Created with Fabric.js 1.6.0-rc.1 1 2 3 4 5 6 7 [[4,5,6,7],[2,3],[1]] Reverse Level Order Traversal:

Example 2:

Created with Fabric.js 1.6.0-rc.1 12 7 1 9 10 5 [[9,10,5],[7,1],[12]] Reverse Level Order Traversal:

Try it yourself #

Try solving this question here:

Output

1.044s

Reverse level order traversal: deque([])

Solution #

This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only difference will be that instead of appending the current level at the end, we will append the current level at the beginning of the result list.

Code #

Here is what our algorithm will look like; only the highlighted lines have changed. Please note that, for Java, we will use a LinkedList instead of an ArrayList for our result list. As in the case of ArrayList, appending an element at the beginning means shifting all the existing elements. Since we need to append the level array at the beginning of the result list, a LinkedList will be better, as this shifting of elements is not required in a LinkedList. Similarly, we will use a double-ended queue (deque) for Python, C++, and JavaScript.

Output

0.461s

Reverse level order traversal: deque([[9, 10, 5], [7, 1], [12]])

Time complexity #

The time complexity of the above algorithm is O(N)O(N), where ā€˜N’ is the total number of nodes in the tree. This is due to the fact that we traverse each node once.

Space complexity #

The space complexity of the above algorithm will be O(N)O(N) as we need to return a list containing the level order traversal. We will also need O(N)O(N) space for the queue. Since we can have a maximum of N/2N/2 nodes at any level (this could happen only at the lowest level), therefore we will need O(N)O(N) space to store them in the queue.

Mark as Completed
←    Back
Binary Tree Level Order Traversal (easy)
Next    →
Zigzag Traversal (medium)